#include <reg52.h>
#defined uchar unsigned char
#defined uint unsigned int

// 数码管16进制数形
uchar code nums[] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71};

// 数码管显示位地址
unchar code digits[] = {0xfe, 0xfd, 0xfb, 0xf7, 0xef, 0xdf, 0xbf, 0x7f};

// 锁定数码管段显
void lock_num() 
{
    P2 = P2 | 0x40;
	P2 = P2 & 0xbf;
}

// 锁定数码管位显
void lock_digit() 
{
    P2 = P2 | 0x80;
	P2 = P2 & 0x7f;
}

// 软件延时
void delay_by_code(uint i) {
	uint m,n;
	for(m=i;m>0;m--)
		for(n=90;n>0;n--);
}

// 矩阵键盘按键扫描, 返回值为第N个按下的键
uchar code rows[] = {0x0e, 0x0d, 0x0b, 0x07};
uchar code cols[] = {0xe0, 0xd0, 0xb0, 0x70};
uchar get_key() {
	uchar col = -1;
	uchar row = -1;

	while(1)
	{
		P3 = 0xf0;
		delay_by_code(20);
		
		for (col=0; col<sizeof(cols); col++)
		{
			if (P3 == cols[col]) 
			{
				P3 = 0x0f;
				delay_by_code(20);
				for (row=0; row<sizeof(rows); row++)
				{
					if (P3 == rows[row]) 
					{
						while(P3 == rows[row]);
						return row*4+col;
					}
				} 
			}
		}
	}
}